package gdut.stream.last;

import java.util.ArrayList;
import java.util.Optional;
import java.util.function.BinaryOperator;

public class ReduceTest {
    public static void main(String[] args) {
        ArrayList<Integer> integers = new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            integers.add(i);
        }
//        reduce操作，获取流中的最大值，设置初始值为最小值
//        System.out.println(Integer.MIN_VALUE);
        Integer result = integers.stream()
                .reduce(Integer.MIN_VALUE, new BinaryOperator<Integer>() {
                    @Override
                    public Integer apply(Integer result, Integer element) {
                        return result > element ? result : element;
                    }
                });
        System.out.println(result);
//        reduce操作，获取流中的最小值，不设置默认值，利用重载方法，底层设置默认值为流中的第一个值
        Optional<Integer> result2 = integers.stream()
                .reduce(new BinaryOperator<Integer>() {
                    @Override
                    public Integer apply(Integer result, Integer element) {
                        return result > element ? element : result;
                    }
                });
        result2.ifPresent(res -> System.out.println(res));
    }
}
